package org.atlantis.netty.http;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpVersion;

public class HttpClient {

	private static final String DEMO_URL = "http://localhost:8080?username=seenoevil.cn@gmail.com&query=SNE";

	public static void main(String[] args) throws Exception {
		URI uri = new URI(DEMO_URL);
		String host = uri.getHost() == null ? "localhost" : uri.getHost();
		int port = uri.getPort() == -1 ? 8080 : uri.getPort();

		ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

		bootstrap.setPipelineFactory(new HttpClientPipeline());
		// 尝试连接到服务器
		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
		// 等待连接完成，这里得到的Channel是客户端的Channel
		Channel channel = future.awaitUninterruptibly().getChannel();
		if (!future.isSuccess()) {
			future.getCause().printStackTrace();
			bootstrap.releaseExternalResources();
			return;
		}

		// 准备HTTP请求
		HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
		request.setHeader(HttpHeaders.Names.HOST, host);
		request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
		request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
		// 设定一些Cookie
		CookieEncoder httpCookieEncoder = new CookieEncoder(false);
		httpCookieEncoder.addCookie("username-cookie", "Atlantis");
		httpCookieEncoder.addCookie("userage-cookie", "23");
		request.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
		
		channel.write(request);
		channel.getCloseFuture().awaitUninterruptibly();
		bootstrap.releaseExternalResources();
	}
}
